package com.relax.reentrantLock;

import javax.lang.model.element.VariableElement;
import java.util.ArrayList;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReadWrireLock {
    // 线程不安全的List
    private ArrayList<String> list = new ArrayList<String>();
    // 读写锁
    private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
    // 获取读锁
    private final ReentrantReadWriteLock.ReadLock  readLock = lock.readLock();
    // 获取写锁
    private final ReentrantReadWriteLock.WriteLock  writeLock = lock.writeLock();



    // 往集合中添加元素，写锁
    public void add(String str) {
        writeLock.lock();
        try {
            list.add(str);
        } finally {
            writeLock.unlock();
        }
    }



    // 根据索引获取集合中某个元素，读锁
    public String get(int index) {
        readLock.lock();
        try {
            return list.get(index);
        } finally {
            readLock.unlock();
        }
    }
}
